package com.cqupt.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.cqupt.mapper.WordMapper;
import com.cqupt.model.pojo.Word;
import com.cqupt.model.pojo.WordBook;
import com.cqupt.service.WordBookService;
import com.cqupt.service.WordService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

public class WordListener implements ReadListener<Word> {

    private final int BATCH_COUNT = 100;
    private final List<Word> list = new ArrayList<>(BATCH_COUNT);
    private final List<WordBook> list2 = new ArrayList<>(BATCH_COUNT);


    private WordService wordService;
    private WordBookService wordBookService;
    private Integer bookId;

    public WordListener(WordService wordService, WordBookService wordBookService, Integer bookId) {
        this.wordService = wordService;
        this.wordBookService = wordBookService;
        this.bookId = bookId;
    }


    @Override
    public void invoke(Word word, AnalysisContext analysisContext) {
        list.add(word);
        if (list.size() >= BATCH_COUNT) {
            wordService.saveBatch(list);
            list.forEach(item -> {
                WordBook wordBook = new WordBook();
                wordBook.setBookId(bookId);
                wordBook.setWordId(item.getId());
                list2.add(wordBook);
            });
            wordBookService.saveBatch(list2);
            list.clear();
            list2.clear();
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (!list.isEmpty()) {
            wordService.saveBatch(list);
            list.forEach(item -> {
                WordBook wordBook = new WordBook();
                wordBook.setBookId(bookId);
                wordBook.setWordId(item.getId());
                list2.add(wordBook);
            });
            wordBookService.saveBatch(list2);
            list.clear();
            list2.clear();
        }
    }
}
